<?php
/**
 * 生成xml时进行实体转义
 * @param	string $string	未转义字符串
 * @return	string 			转义后字符串
 * @author	FrankKung <Frank@kofj.net>
 */
function xmlEncode($string) {
	$string = str_replace("&", "&amp;", $string);
	$string = str_replace("<", "&lt;", $string);
	$string = str_replace(">", "&gt;", $string);
	$string = str_replace("'", "&apos;", $string);
	$string = str_replace("/", '&quot;', $string);
	return $string;
}

/**
 * 格式化关键字为<tag>标签
 * @param	string $keywords	关键字
 * @return	string 			html字符串
 * @author	FrankKung <Frank@kofj.net>
 */
function words2tag($words) {
	$tagArray = explode(',', $words);
	$tags = "";
	foreach ($tagArray as $k => $word) {
		$word = str_replace("\n", "", $word);
		if ($k < 20) {
			$tags .= "<tag>{$word}</tag>";
		}
	}
	return "{$tags}\r\n";
}

/**
 * 格式化字节大小
 * @param  number $size      字节数
 * @param  string $delimiter 数字和单位分隔符
 * @return string            格式化后的带单位的大小
 * @author 麦当苗儿 <zuojiazi@vip.qq.com>
 */
 function formatBytes($size, $delimiter = '') {
    $units = array('B', 'KB', 'MB', 'GB', 'TB', 'PB');
    for ($i = 0; $size >= 1024 && $i < 6; $i++) $size /= 1024;
    return round($size, 2) . $delimiter . $units[$i];
 }

/**
 * 下载链接转换
 * @param string $hash 哈希值
 * @param string $id 记录ID
 * @param string $name 网站名称 BLOGNAME
 * @param string $site 网站地址 BLOGURL
 * @param string $rss 网站rss源 BLOGRSS
 * @author FrankKung <Frank@kofj.net>
 */
function ping($hash, $id, $list = "|google|baidu|", $name="神码磁力链接搜索引擎", $site="http://www.codeit.cn/", $rss="http://www.codeit.cn/rss.xml") {
	if (!extension_loaded('curl'))return;
	$page = "{$site}torrent/{$hash}";

	$xml_rpc_data = 'EOF
<?xml version="1.0" encoding="UTF-8"?>
<methodCall>
	<methodName>weblogUpdates.extendedPing</methodName>
	<params>
		<param><value>{$name}</value></param>
		<param><value>{$site}</value></param>
		<param><value>{$page}</value></param>
		<param><value>{$rss}</value></param>
	</params>
</methodCall>
EOF';
	
	$xmlparser = xml_parser_create();
	if (strpos($list, 'google') !== false)
	{
		$ping_google = curl_init();
		$url = 'http://blogsearch.google.com/ping/RPC2';
		$header = array('Content-Type: text/xml; charset=UTF-8', 'User-Agent: Codeit.cn PingBot/1.0');
		curl_setopt($ping_google, CURLOPT_URL, $url);
		curl_setopt($ping_google, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($ping_google, CURLOPT_TIMEOUT, 10);
		curl_setopt($ping_google, CURLOPT_HTTPHEADER, $header);
		curl_setopt($ping_google, CURLOPT_POST, 1);
		curl_setopt($ping_google, CURLOPT_POSTFIELDS, $xml_rpc_data);
		//$res = curl_exec($ping_google);var_dump($res);
		xml_parse_into_struct($xmlparser, curl_exec($ping_google), $google);
		//print_r($google);
		$ret['google'] = !$google[8]['value'];
	}

	if (strpos($list, 'baidu') !== false)
	{
		$ping_baidu = curl_init();
		$url = 'http://ping.baidu.com/ping/RPC2';
		$header = array('Content-Type: text/xml; charset=UTF-8', 'User-Agent: Codeit.cn PingBot/1.0');
		curl_setopt($ping_baidu, CURLOPT_URL, $url);
		curl_setopt($ping_baidu, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($ping_baidu, CURLOPT_TIMEOUT, 10);
		curl_setopt($ping_baidu, CURLOPT_HTTPHEADER, $header);
		curl_setopt($ping_baidu, CURLOPT_POST, 1);
		curl_setopt($ping_baidu, CURLOPT_POSTFIELDS, $xml_rpc_data);
		$res = curl_exec($ping_baidu);

		xml_parse_into_struct($xmlparser, $res, $baidu);
		//var_dump($baidu, $res);
		$ret['baidu'] = !$baidu[4]['value'];
	}
	$ret['id'] = $id;
	return $ret;
}

/**
 * 下载链接转换
 * @param string 下载地址
 * @return array 下载地址数组
 * @author FrankKung <Frank@kofj.net>
 */
function zhuanhuan($url){
	if(empty($url)) return $result;
	$urlodd=explode(':',$url,2);
	$head=strtolower($urlodd[0]);
	$behind=$urlodd[1];
	if($head=="thunder"){
		$behind = mb_ereg_replace('//', '', $behind);
		$url=substr(base64_decode($behind),2,-2);
	}else if($head=="flashget"){
		$behind = mb_ereg_replace('//', '', $behind);
		$url1=explode('&',$behind,2);
		$url=substr(base64_decode($url1[0]),10,-10);
	}else if($head=="qqdl"){
		$behind = mb_ereg_replace('//', '', $behind);
		$url=base64_decode($behind);
	}elseif( in_array($head, array('magnet','http','https','ftp','mms','rtsp')) ){
		$url=array(
			'thunder'=>"thunder://".base64_encode("AA".$url."ZZ"),
			'flashget'=>"Flashget://".base64_encode("[FLASHGET]".$url."[FLASHGET]")."&aiyh",
			'qqdl'=>"qqdl://".base64_encode($url)
		);
	}else{
		return '';
	}
	return $url;
}

/**
 * 移动设备判定
 * @return boolean 1是0否
 * @author FrankKung <Frank@kofj.net>
 */
function isMobile(){
	$useragent=isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : '';
	$useragent_commentsblock=preg_match('|\(.*?\)|',$useragent,$matches)>0?$matches[0]:'';      
	function CheckSubstrs($substrs,$text){
		foreach($substrs as $substr)
			if(false!==strpos($text,$substr)){
				return true;
			}
			return false;
	}
	$mobile_os_list = array(
		'Google Wireless Transcoder',
		'Windows CE',
		'WindowsCE',
		'Symbian',
		'Android',
		'armv6l',
		'armv5',
		'Mobile',
		'CentOS',
		'mowser',
		'AvantGo',
		'Opera Mobi',
		'J2ME/MIDP',
		'Smartphone',
		'Go.Web',
		'Palm',
		'iPAQ'
	);
	$mobile_token_list = array(
		'Profile/MIDP',
		'Configuration/CLDC-',
		'160×160',
		'176×220',
		'240×240',
		'240×320',
		'320×240',
		'UP.Browser',
		'UP.Link',
		'SymbianOS',
		'PalmOS',
		'PocketPC',
		'SonyEricsson',
		'Nokia',
		'BlackBerry',
		'Vodafone',
		'BenQ',
		'Novarra-Vision',
		'Iris',
		'NetFront',
		'HTC_',
		'Xda_',
		'SAMSUNG-SGH',
		'Wapaka',
		'DoCoMo',
		'iPhone',
		'iPod'
	);
		
	$found_mobile=CheckSubstrs($mobile_os_list,$useragent_commentsblock) || CheckSubstrs($mobile_token_list,$useragent);
	if ($found_mobile){
		return true;
	}else{
		return false;
	}
}

/**
 * 截取摘要
 * @param string $str 文本内容
 * @param int $num 截取字数
 * @param string $tail 截取后后面还有内容时显示的文字
 * @return string 返回摘要
 * @author FrankKung <Frank@kofj.net>
 */
function getSummary($str,$num=150,$tail='')
{
	static $charset='utf-8'; // 编码，根据自己的修改，不过一般都是utf-8吧
	$str=str_replace("\n", " ", $str);
	// 先strip_tags()去除html标签，再html_entity_decode()把html实体转成字符，ltrim是去除左边所有空格
	$str=ltrim(html_entity_decode(strip_tags($str),ENT_QUOTES,'utf-8'));
	if(mb_strlen($str,$charset)<=$num)
	{
		return $str;
	}
	else
	{
		return mb_substr($str,0,$num,$charset).$tail;
	}
}

// 格式化Unix时间戳
function formatTime($time, $format="Y年m月d日 H:i:s") {
	return date($format, $time);
}

// 格式化列表
function formatList($value='') {
	$wordsArray = explode(',', $value);//var_dump($value,$wordsArray);
	$listString = "";
	foreach ($wordsArray as $index => $word) {
		$word = str_replace("\n", "", $word);
		$listString .= "							<tr><td>{$word}</td></tr>\r\n";
	}
	return $listString;
}

// 获取关键字链接
function getKeywordsLink($value='') {
	$keyWordsArray = explode(',', $value);
	$linkString = "";
	foreach ($keyWordsArray as $keyWord) {
		$linkString .= "<a href=\"/list/{$keyWord}/1\" title=\"{$keyWord}\">{$keyWord}</a>  ";
	}
	return $linkString;
}
// 高亮
function highlight($content,$key) {
	//ini_set('memory_limit', '32M');
	set_time_limit(0);
	$k_fi=substr($key,0,1);    //取得关键词第一个字符
	$k_len=strlen($key);   //计算关键词字数
	$l_len=strlen($content);    //计算备查文章字数
	
	for($l_n=0;$l_n<$l_len;$l_n++) { //根据备查文章字数开始循环
		$l_s=substr($content,$l_n,1);  //取得备查文章当前字符
		if($l_s=="<") {   //如果这个字符是标签的开始的话
			while($l_s!=">") { //我们就寻找这个标签的关闭
				$con.=$l_s;  //导入结果
				$l_n++;  //当然要开始取备查文章的下一个字符
				$l_s=substr($content,$l_n,1);
			}

			$con.=$l_s;
		} elseif($l_s==$k_fi) { //如果这个字符与关键词第一个字符相同的话  
			$l_key=substr($content,$l_n,$k_len);  //取备查文章当前位置是否匹配关键词
			if($l_key!=$key){
				$con.=$l_s;  //导入结果
			} else { //如果匹配
				$l_n+=$k_len-1;  //计数跳过相应字数
				$con .= "<em class=\"highlight\">{$key}</em>";
				//$con.="<span style=\"color:hsl(0, 100%, 40%);\">";
				//$con.=$key;
				//$con.="</span>";  //加亮关键词
			}
		} else {
			$con.=$l_s;  //导入结果
		}
	}

	return $con;
 }


 // 获取分组标题
 function getGroupTitle($id='') {
 	$map['id'] = $id;
 	return D('Group')->where($map)->getField('title');
 }

 function getStatus($status, $imageShow = true) {
 	switch ($status) {
 		case 0 :
 			$showText = '禁用';
 			$showImg = '<IMG SRC="'.__ROOT__.'/Public/images/locked.gif" WIDTH="20" HEIGHT="20" BORDER="0" ALT="禁用">';
 			break;
 		case 2 :
 			$showText = '待审';
 			$showImg = '<IMG SRC="'.__ROOT__.'/Public/images/prected.gif" WIDTH="20" HEIGHT="20" BORDER="0" ALT="待审">';
 			break;
 		case - 1 :
 			$showText = '删除';
 			$showImg = '<IMG SRC="'.__ROOT__.'/Public/images/del.gif" WIDTH="20" HEIGHT="20" BORDER="0" ALT="删除">';
 			break;
 		case 1 :
 		default :
 			$showText = '正常';
 			$showImg = '<IMG SRC="'.__ROOT__.'/Public/images/ok.gif" WIDTH="20" HEIGHT="20" BORDER="0" ALT="正常">';

 	}
 	return ($imageShow === true) ?  $showImg  : $showText;

 }

 function showStatus($status, $id, $callback="", $url, $dwz) {
 	switch ($status) {
 		case 0 :
 			$info = '<a href="'.$url.'/resume/id/' . $id . '/navTabId/'.$dwz.'" target="ajaxTodo" callback="'.$callback.'">恢复</a>';
 			break;
 		case 2 :
 			$info = '<a href="'.$url.'/resume/id/' . $id . '/navTabId/'.$dwz.'" target="ajaxTodo" callback="'.$callback.'">恢复</a>';
 			break;
 		case 1 :
 			$info = '<a href="'.$url.'/forbid/id/' . $id . '/navTabId/'.$dwz.'" target="ajaxTodo" callback="'.$callback.'">禁用</a>';
 			break;
 		case - 1 :
 			$info = '<a href="'.$url.'/recycle/id/' . $id . '/navTabId/'.$dwz.'" target="ajaxTodo" callback="'.$callback.'">还原</a>';
 			break;
 	}
 	return $info;
 }

 function getGroupName($id) {
 	if (empty ( $id )) {
 		return '未分组[不显示]';
 	}
 	if (isset ( $_SESSION ['nodeGroupList'] )) {
 		return $_SESSION ['nodeGroupList'] [$id];
 	}
 	$Group = D ( "Group" );
 	$list = $Group->getField ( 'id,title' );
 	$_SESSION ['nodeGroupList'] = $list;
 	$name = $list [$id];
 	return $name;
 }

 /**
  * 字符串截取，支持中文和其他编码
  * @static
  * @access public
  * @param string $str 需要转换的字符串
  * @param string $start 开始位置
  * @param string $length 截取长度
  * @param string $charset 编码格式
  * @param string $suffix 截断显示字符
  * @return string
  */
 function msubstr($str, $start=0, $length=45, $charset="utf-8", $suffix=true) {
 	if(function_exists("mb_substr"))
 		$slice = mb_substr($str, $start, $length, $charset);
 	elseif(function_exists('iconv_substr')) {
 		$slice = iconv_substr($str,$start,$length,$charset);
 		if(false === $slice) {
 			$slice = '';
 		}
 	}else{
 		$re['utf-8']   = "/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xff][\x80-\xbf]{3}/";
 		$re['gb2312'] = "/[\x01-\x7f]|[\xb0-\xf7][\xa0-\xfe]/";
 		$re['gbk']    = "/[\x01-\x7f]|[\x81-\xfe][\x40-\xfe]/";
 		$re['big5']   = "/[\x01-\x7f]|[\x81-\xfe]([\x40-\x7e]|\xa1-\xfe])/";
 		preg_match_all($re[$charset], $str, $match);
 		$slice = join("",array_slice($match[0], $start, $length));
 	}
 	return $suffix ? $slice.'...' : $slice;
 }

 /**
  * 时间戳格式化
  * @param int $time
  * @return string 完整的时间显示
  * @author FrankKung <kongfanjian@andlisoft.com>
  */
 function timeFormat($time = NULL,$format='Y-m-d H:i:s'){
 	$time = $time === NULL ? NOW_TIME : intval($time);
 	return date($format, $time);
 }

 /**
  * 判断变量是否为空
  * @param mixed $var 变量
  * @return true/false
  */
 function is_empty($var, $allow_false = false, $allow_ws = false) {
 	if (!isset($var) || is_null($var) || ($allow_ws == false && trim($var) == "" && !is_bool($var)) || ($allow_false === false && is_bool($var) && $var === false) || (is_array($var) && empty($var))) {  
 		return true;
 	} else {
 		return false;
 	}
 }
